﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Data;
using System.Windows.Interactivity;

namespace nRoute.Samples.Sudoku.Behaviors
{
    public class SetParentGridPosBehavior 
        : Behavior<FrameworkElement>
    {
        public static readonly DependencyProperty RowProperty =
            DependencyProperty.Register("Row", typeof(int), typeof(SetParentGridPosBehavior),
            new PropertyMetadata(null));

        public static readonly DependencyProperty ColProperty =
            DependencyProperty.Register("Col", typeof(int), typeof(SetParentGridPosBehavior),
            new PropertyMetadata(null));

#region Properties

        public int Row
        {
            get { return (int)GetValue(RowProperty); }
            set { SetValue(RowProperty, value); }
        }

        public int Col
        {
            get { return (int)GetValue(ColProperty); }
            set { SetValue(ColProperty, value); }
        }

#endregion

#region Overrides

        protected override void OnAttached()
        {
            // resolve the bindings and get the container
            base.OnAttached();

            // we need to wait till the associate obj is attached to its visual parent
            this.AssociatedObject.Loaded += (s, e) =>
            {
                // set the col and row attached properties
                var _container = ResolveContentPresenter();
                if (_container != null)
                {
                    Grid.SetColumn(_container, Col);
                    Grid.SetRow(_container, Row);
                }
            };
        }

#endregion

#region Helpers

        ContentPresenter ResolveContentPresenter()
        {
            DependencyObject _element = VisualTreeHelper.GetParent(this.AssociatedObject);
            while (_element != null)
            {
                if (typeof(ContentPresenter).IsAssignableFrom(_element.GetType()))
                {
                    return _element as ContentPresenter;
                }
                _element = VisualTreeHelper.GetParent(_element);
            }
            return null;
        }

#endregion

    }
}
